package yongxin.controller.check;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.util.ResourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import yongxin.entity.check.CheckPurchaseEntity;
import yongxin.entity.check.ContractEntity;
import yongxin.entity.check.ContractProcutEntity;
import yongxin.entity.check.ItemEntity;
import yongxin.entity.processreport.ProcessReportEntity;
import yongxin.service.check.CheckPurchaseServiceI;

/**   
 * @Title: Controller
 * @Description: 采购申请 审批
 * @author zhangdaihao
 * @date 2015-04-29 21:00:09
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/purchaseCheckController")
public class PurchaseCheckController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(PurchaseCheckController.class);

	@Autowired
	private SystemService systemService;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 采购列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "purchase")
	public ModelAndView processReport(HttpServletRequest request) {
		
		return new ModelAndView("yongxin/check/purchaseList");
		
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(ProcessReportEntity processReport,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		

		 String sql  = " select * from  ";
				sql +="  OPENQUERY ( RemoteServer , ";
				sql +="' ";
				sql +=" select  v1.fbillno AS FbillNo,v1.Fstatus AS Fstatus,v1.FInterID AS FInterID,v1.FCheckerID AS FCheckerID, ";
				sql +=" t4.FName AS FDeptIDName,t8.FName AS FRequesterIDName,v1.FDate as FDate,v1.FCheckTime AS FCheckTime, ";
				sql +=" v1.FMultiCheckLevel1 AS FMultiCheckLevel1,v1.FMultiCheckDate1 AS FMultiCheckDate1,v1.FNote AS FNote,t10.FName AS FBillerID_DSPName ";
				sql +=" from AIS2009.dbo.POrequest v1  ";
				sql +="  LEFT OUTER JOIN AIS2009.dbo.t_Department t4 ON     v1.FDeptID = t4.FItemID   AND t4.FItemID <>0  ";
				sql +="  LEFT OUTER JOIN AIS2009.dbo.ICMO t5 ON     v1.FSCBillInterID = t5.FInterID   AND t5.FInterID <>0  ";
				sql +="  LEFT OUTER JOIN AIS2009.dbo.t_Submessage t17 ON     v1.FMRP = t17.FInterID   AND t17.FInterID <>0  ";
				sql +=" LEFT OUTER JOIN AIS2009.dbo.t_Emp t8 ON     v1.FRequesterID = t8.FItemID   AND t8.FItemID <>0  ";
				sql +="  LEFT OUTER JOIN AIS2009.dbo.t_User t9 ON     v1.FCheckerID = t9.FUserID   AND t9.FUserID <>0  ";
				sql +="  LEFT OUTER JOIN AIS2009.dbo.t_User t10 ON     v1.FBillerID = t10.FUserID   AND t10.FUserID <>0 ";  
				sql +="  where  v1.fstatus = 0 and v1.FCurCheckLevel = 1 ";
				sql +="   ') ";
				
				List<Map<String, Object>> maplist = null;
				List<Map<String, Object>> allmaplist = null;

				try
				{

					allmaplist = systemService.findForJdbc(sql);
					maplist = systemService.findForJdbcParam(sql, dataGrid.getPage(), dataGrid.getRows());

				} catch (Exception ex)
				{

				}
		 
				dataGrid.setTotal(allmaplist.size());
				dataGrid.setResults(maplist);
				TagUtil.datagrid(response, dataGrid);
		
		
	}


	
	/**
	 * 工序汇报列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(HttpServletRequest req) {
		
			String FInterID = req.getParameter("FInterID");
			int id = Integer.parseInt(FInterID);
		    Object[] object=new Object[1];
		    object[0]=id;
		    String sql  = " select * from  ";
			sql +="  OPENQUERY ( RemoteServer , ";
			sql +="' ";
			sql +=" select  v1.fbillno AS FbillNo,v1.Fstatus AS Fstatus,v1.FInterID AS FInterID,v1.FCheckerID AS FCheckerID, ";
			sql +=" t4.FName AS FDeptIDName,t8.FName AS FRequesterIDName,v1.FDate as FDate,v1.FCheckTime AS FCheckTime, ";
			sql +=" v1.FMultiCheckLevel1 AS FMultiCheckLevel1,v1.FMultiCheckDate1 AS FMultiCheckDate1,v1.FNote AS FNote,t10.FName AS FBillerID_DSPName  ";
			sql +=" from AIS2009.dbo.POrequest v1  ";
			sql +="  LEFT OUTER JOIN AIS2009.dbo.t_Department t4 ON     v1.FDeptID = t4.FItemID   AND t4.FItemID <>0  ";
			sql +="  LEFT OUTER JOIN AIS2009.dbo.ICMO t5 ON     v1.FSCBillInterID = t5.FInterID   AND t5.FInterID <>0  ";
			sql +="  LEFT OUTER JOIN AIS2009.dbo.t_Submessage t17 ON     v1.FMRP = t17.FInterID   AND t17.FInterID <>0  ";
			sql +=" LEFT OUTER JOIN AIS2009.dbo.t_Emp t8 ON     v1.FRequesterID = t8.FItemID   AND t8.FItemID <>0  ";
			sql +="  LEFT OUTER JOIN AIS2009.dbo.t_User t9 ON     v1.FCheckerID = t9.FUserID   AND t9.FUserID <>0  ";
			sql +="  LEFT OUTER JOIN AIS2009.dbo.t_User t10 ON     v1.FBillerID = t10.FUserID   AND t10.FUserID <>0 ";  
			sql +="  where  v1.FInterID = %s ";
			sql +="   ') ";
				
			sql=String.format(sql, id);
			// 根据	FInterID  查询采购信息
				List<Map<String,Object>>  mapList= systemService.findForJdbc(sql);
				CheckPurchaseEntity entity = new CheckPurchaseEntity();
				
				for (int i=0;i<mapList.size();i++)
				{
				       Map  map=(Map)mapList.get(i);
				       entity.setFdeptidname((String) map.get("FDeptIDName"));
				       entity.setFbillno((String) map.get("FbillNo"));
				       entity.setFdate((Date) map.get("Fdate"));
				       entity.setFnote((String) map.get("Fnote"));
				       entity.setFrequesteridname((String) map.get("FRequesterIDName"));
				       entity.setFbilleridspname((String) map.get("FBillerID_DSPName"));
				}
				entity.setId(String.valueOf(id));
				req.setAttribute("checkPurchasePage", entity);
			
				
				 String sql2   =  " select * from  ";
				 sql2 += " OPENQUERY ( RemoteServer , ";
				 sql2 += "  ' ";
				 sql2 += " 	 SELECT POrequestEntry.FInterID, POrequestEntry.FEntryID, POrequestEntry.FItemID,  ";
				 sql2 += " 	 t002.FQtyDecimal, t002.FPriceDecimal, t002.FUnitGroupID, t002.FNumber as  FItemIDNumber, t002.FName as  FItemIDName, ";
				 sql2 += "  t002.Fname as FItemName, t002.Fmodel as FItemModel, POrequestEntry.FAuxPropID, t005.FNumber as  FAuxPropIDNumber, ";
				 sql2 += "  t005.FName as  FAuxPropIDName, t006.FName as FBaseUnit, POrequestEntry.FQty, POrequestEntry.FUnitID, ";
				 sql2 += "  t008.FNumber as  FUnitIDNumber, t008.FName as  FUnitIDName, Convert(decimal(18,4),POrequestEntry.Fauxqty) AS Fauxqty, t010.FName as FSecUnitID, ";
				 sql2 += "  POrequestEntry.FSecCoefficient, POrequestEntry.FSecQty, POrequestEntry.FAPurchTime, ";
				 sql2 += "  POrequestEntry.FEntrySelfP0125, t014.FNumber as  FEntrySelfP0125Number, t014.FName as  FEntrySelfP0125Name, ";
				 sql2 += "  POrequestEntry.Fuse, POrequestEntry.FSupplyID, t016.FNumber as  FSupplyIDNumber, t016.FName as  FSupplyIDName,  ";
				 sql2 += " 	 t002.FFixLeadTime as FLeadTime, POrequestEntry.FFetchTime, POrequestEntry.FPlanOrderInterID, POrequestEntry.FSourceBillNo, ";
				 sql2 += "  POrequestEntry.FSourceTranType, POrequestEntry.FSourceInterId, POrequestEntry.FSourceEntryID,  ";
				 sql2 += "  t002.FAuxClassID as FAuxPropCls, POrequestEntry.FMrpLockFlag, POrequestEntry.FEntrySelfP0126, POrequestEntry.FBrNo ";
				 sql2 += "  FROM AIS2009.dbo.POrequestEntry POrequestEntry join AIS2009.dbo.t_ICItem  t002 on t002.FItemID = POrequestEntry.FItemID AND t002.FItemID <>0  "; 
				 sql2 += "   left join AIS2009.dbo.t_AuxItem  t005 on t005.FItemID = POrequestEntry.FAuxPropID AND t005.FItemID <>0   ";
				 sql2 += "   left join AIS2009.dbo.t_MeasureUnit t006 on  t006.FItemID=t002.FUnitID  AND t006.FItemID<>0  "; 
				 sql2 += "   left join AIS2009.dbo.t_MeasureUnit  t008 on t008.FItemID = POrequestEntry.FUnitID AND t008.FItemID <>0 ";  
				 sql2 += "   left join AIS2009.dbo.t_MeasureUnit t010 on  t010.FItemID=t002.FSecUnitID  AND t010.FItemID<>0  "; 
				 sql2 += "   left join AIS2009.dbo.t_Department  t014 on t014.FItemID = POrequestEntry.FEntrySelfP0125 AND t014.FItemID <>0   ";
				 sql2 += "   left join AIS2009.dbo.t_Supplier  t016 on t016.FItemID = POrequestEntry.FSupplyID AND t016.FItemID <>0  ";
				 sql2 += "   WHERE POrequestEntry.FInterID IN ( %s ) ";
				 sql2 += "   ORDER BY POrequestEntry.FEntryID ";
				 sql2 += "   ') ";
                 
				 sql2=String.format(sql2, id);
			// 根据	FContractID  查询产品信息
			List<Map<String,Object>>  mapList2= systemService.findForJdbc(sql2);
			List<ItemEntity> list = new ArrayList<ItemEntity>();
			for (int i=0;i<mapList2.size();i++)
			{      
			       Map  map=(Map)mapList2.get(i);
			       ItemEntity entity2= new ItemEntity();
			       entity2.setFitemidnumber((String) map.get("FItemIDNumber"));
			       entity2.setFitemidname((String) map.get("FItemIDName"));
			       entity2.setFunitidname((String) map.get("FUnitIDName"));
			       entity2.setFauxqty((BigDecimal) map.get("Fauxqty"));
			       entity2.setFapurchtime((Date) map.get("FAPurchTime"));
			       entity2.setFentryselfp0125name((String) map.get("FEntrySelfP0125Name"));
			       entity2.setFleadtime( (Timestamp) map.get("FFetchTime"));
			       entity2.setFfetchtime((Date) map.get("FFetchTime"));
			       entity2.setFentryselfp0126((String) map.get("FEntrySelfP0126"));
			       list.add(entity2);
			}
			req.setAttribute("itemList", list);
			
			return new ModelAndView("yongxin/check/purchaseDetail");
		
	}
	
	
	
	/**
	 * 审核
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "check")
	@ResponseBody
	public AjaxJson check(HttpServletRequest request) {
		
		AjaxJson j = new AjaxJson();
		String FInterID = request.getParameter("id");
		
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
		String checkDate = formatter.format(new Date());
		
		String userId = "";
		//获取登录用户
		TSUser user = ResourceUtil.getSessionUser();//(TSUser) request.getSession().getAttribute("loginUser");
		if(user.getUserName().equals("yuanxl")){
			
			userId = "16446";
			
		}else{
			
			userId = "16501";
		}
		
		
	String  sql =  " SET XACT_ABORT ON ;Update RemoteServer.AIS2009.dbo.POrequest Set FMultiCheckLevel2 = 16501, FMultiCheckDate2 = ?, ";
			sql += " FCurCheckLevel = (Case When 2 < FCurCheckLevel Then FCurCheckLevel Else 2 End),";
			sql += " FCheckerID=?,FStatus=1,FCheckTime=? ";
			sql += " Where FInterID = ? ";
		
			systemService.executeSql(sql,checkDate,userId,checkDate,FInterID);
		message = "审批成功";
		
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 审核
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "uncheck")
	@ResponseBody
	public AjaxJson uncheck(HttpServletRequest request) {
		
		AjaxJson j = new AjaxJson();
		String FInterID = request.getParameter("id");
		
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
		String checkDate = formatter.format(new Date());
	//	TSUser user = (TSUser) request.getSession().getAttribute("loginUser");
	//	String checker = user.getUserName();
		
		
		
		String	sql = " SET XACT_ABORT ON ; Update RemoteServer.AIS2009.dbo.POrequest Set FMultiCheckLevel1 = Null , FMultiCheckDate1 = Null ,  ";
				sql += "FCurCheckLevel = (Case When 2 < FCurCheckLevel Then FCurCheckLevel Else 0 End) ";
			    sql += " Where FInterID = ? ";
		     
	    systemService.executeSql(sql,FInterID);
		message = "驳回成功";
		
		j.setMsg(message);
		return j;
	}
}
